<template>
  <div>
    <div class="all-wrap">
      <div class="all-title">歌曲管理</div>
      <div class="top-controllers" style="margin-bottom: 4px;">
        <el-select v-model="selectOwner" filterable clearable placeholder="选择歌手" style="width: 200px;margin-right: 20px;" @change="selectChange">
          <el-option v-for="item in singerList" :key="item.id" :label="item.singerName" :value="item.id" />
        </el-select>
        <el-input v-model="searchValue" clearable class="w-50 m-2" placeholder="请输入歌曲名称" @clear="inputClear" />
        <el-button type="primary" @click="searchClick">搜索</el-button>
        <el-button type="primary" @click="addSingerFN">新增</el-button>
      </div>
    </div>
    <el-table :data="tableData" border style="width: 100%">
      <el-table-column type="index" width="50" />
      <el-table-column prop="title" label="标题"  width="200"> </el-table-column>
      <el-table-column prop="url" label="链接"   width="850"/>
      <el-table-column prop="演唱者" label="演唱者" width="100">
        <template #default="scope">
          <el-tag v-if="scope.row.singer.id != 0">{{ scope.row.singer.singerName }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="Controllers">
        <template #default="scope">
          <el-button type="primary" size="small" @click="editData(scope.row)">修改</el-button>
          <el-popconfirm width="220" confirm-button-text="OK" cancel-button-text="No, Thanks" :icon="InfoFilled"
            icon-color="#626AEF" title="Are you sure to delete this?" @confirm="confirmEvent(scope.row)">
            <template #reference>
              <el-button>Delete</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination v-model:current-page="currentPage" :page-size="10" layout="total, prev, pager, next" :total="dataTotal"
      @current-change="handleCurrentChange" />
    <el-dialog v-model="dialogSong" :title="popTitle">
      <el-form :model="form" ref="ruleFormRef" label-width="100" :rules="rules">
        <el-form-item label="歌曲名" prop="title">
          <el-input v-model="form.title" autocomplete="off" />
        </el-form-item>
        <el-form-item label="演唱者" props="owner">
          <el-select v-model="form.owner" filterable placeholder="Select" style="width: 100%">
            <el-option v-for="item in singerList" :key="item.id" :label="item.singerName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-button :type="musicType?'primary':''" @click="musicType=true">音频链接</el-button><el-button :type="musicType?'':'primary'" @click="musicType=false">上传本地音频</el-button>
        <el-form-item v-show="musicType" label="音频链接" prop="url">
          <el-input v-model="form.url" autocomplete="off" />
        </el-form-item>
        <el-form-item  v-show="!musicType" label="上传音乐">
          <el-upload ref="upload" class="upload-demo" action="/shopApi/admin/uploadSong" :limit="1"
            :on-exceed="handleExceed" :on-success="uploadSuccess" :before-remove="beforeRemove"
            :headers="addHeader"
            v-model:file-list="fileList" :auto-upload="true">
            <template #trigger>
              <el-button type="primary">select file</el-button>
            </template>
            <template #tip>
              <div class="el-upload__tip text-red">
                限制上传一张，多上传会覆盖上一张
              </div>
              <div v-show="form.url">{{ form.url }}</div>
            </template>
          </el-upload>
        </el-form-item>

      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelEdit">取消</el-button>
          <el-button type="primary" @click="submitEdit(ruleFormRef)">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, FormInstance } from 'element-plus'
import { InfoFilled } from '@element-plus/icons-vue'
import { genFileId } from 'element-plus'
import type { UploadInstance, UploadProps, UploadRawFile } from 'element-plus'
import { getSongList, addSong, editSong, deleteSong, getSongsById } from '../apis/song'
import { getSingerList } from '../apis/singer'
const ruleFormRef = ref<FormInstance>()
interface opytion {
  id: number
  singerName: string
}
let singerList = ref<opytion[]>([])
let searchValue = ref('')
let tableData = ref([])
let currentPage = ref(1)
let dataTotal = ref(0)
let dialogSong = ref(false)
let popTitle = ref('新增数据')
let editId = ref(0)
let songer = ref(0)
let musicType=ref(true)
let form = reactive({
  title: '',
  owner: '',
  url: ''
})
const addHeader=reactive({
  Authorization:"Bearer "+sessionStorage.getItem("token")
})
let selectOwner=ref('')
let fileList = ref([])
let rules = reactive({
  title: [
    { min: 1, max: 38, message: "长度在1-18", trigger: 'blur' },
    { required: true, trigger: 'blur' }
  ],
  url:[
  {required:true,trigger:'blur',message:"必填项",pattern:/http:|https:/}
  ]
})

const upload = ref<UploadInstance>()
const handleExceed: UploadProps['onExceed'] = (files) => {
  fileList.value = []
  upload.value!.clearFiles()
  const file = files[0] as UploadRawFile
  file.uid = genFileId()
  upload.value!.handleStart(file)
}
const beforeRemove = (parmas) => {
  form.url = ""
}

const uploadSuccess = (res) => {
  if (res.success != true) return
  form.url = res.url
  // editDataUrl.value=''
}
const cancelEdit = () => {
  dialogSong.value = false
  fileList.value = []
  resetForm()
}
const submitEdit = async (ruleFormRef) => {
  await ruleFormRef.validate(async (valid, fields) => {
    if (valid) {
      if (popTitle.value == "新增数据") {
        let res = await addSong(form)
        if (res.status == 200) {
          ElMessage({
            message: '新增音乐成功',
            type: 'success',
          })
          getDataList()
          dialogSong.value = false
          fileList.value = []
          resetForm()
        }
      } else {
        let data = {
          ...form,
          id: editId.value,
        }
        let res = await editSong(data)
        if (res.status == 200) {
          ElMessage({
            message: '修改音乐成功',
            type: 'success',
          })
          getDataList()
          dialogSong.value = false
          fileList.value = []
          resetForm()
        }
      }
    }
  })
}
const resetForm = () => {
  let empty = {}
  for (let i in form) {
    empty[i] = ''
  }
  Object.assign(form, empty)
}
const searchClick = () => {
  getDataList()
}
const addSingerFN = () => {
  popTitle.value = "新增数据"
  dialogSong.value = true
}
const inputClear = () => {
  currentPage.value = 1
  getDataList()
}
const selectChange=async ()=>{
  // let page=1
  // let pageSize=5
  // let res=await getSongsById({id:selectOwner.value,page,pageSize})
  getDataList()
}
const editData = (row) => {
  popTitle.value = "修改数据"
  editId.value = row.id
  form.title = row.title
  form.owner = row.singer.id
  form.url = row.url
  dialogSong.value = true
}
const confirmEvent = async (row) => {
  let res = await deleteSong({ id: row.id })
    if (res.status == 200) {
      ElMessage({
        message: '删除歌曲成功',
        type: 'success',
      })
      getDataList()
    }
}
const handleCurrentChange = () => {
  getDataList()
}
const getDataList = async () => {
  let res = await getSongList({ id:selectOwner.value,page: currentPage.value, pageSize: 10, title: searchValue.value })
  if (res.status == 200) {
    tableData.value = res.data.list
    dataTotal.value = res.data.total
  }
}
onMounted(() => {
  getDataList()
  getSingerList({ pageSize: 99999 }).then(res => {
    if (res.status == 200) {
      singerList.value = res.data.list
    }
  })
})
</script>
<style lang="less" scoped>
.top-controllers {
  width: 100%;
  height: 30px;

  .w-50 {
    width: 200px;
    margin-right: 20px;
  }
}
</style>